#!/usr/bin/python2
# -*- coding: utf-8 -*-
# Name:     pattern.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Version:  111108

import re, json, types

reg_peak_vars = re.compile(r'([pP][0-9]+)')

def forge_pattern(pattern):
    '''forge pattern function from text
    pattern: the pattern text or pattern dict
    '''
    if type(pattern) == types.StringType:
        pattern = json.loads(pattern)

    peak_vars = list(set(reg_peak_vars.findall('\n'.join(pattern.values()))))
    peak_vars.sort()

    result_pattern =  pattern['result_pattern'].strip().replace('\n', '\n    ')
    if not ('Results.append' in result_pattern or 'R.append' in result_pattern):
        result_pattern = '%s\n    %s' %(result_pattern, 'Results.append({})')

    code_text = ''
    try:
        if peak_vars:
            code_text = '''
%s, = args
''' %','.join(peak_vars)

        code_text += '''
%s
if %s:
    %s
'''   %(
        pattern['pre_defs'],
        pattern['diagnostic_pattern'].replace('\n', ' '),
        result_pattern,
        )
    except:
        pass
    #print code_text
    return (len(peak_vars), code_text)

if __name__ == '__main__':
    pass
